package com.ae.putingotdown.net;

import com.ae.putingotdown.util.PutItemAction;
import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.network.PacketBuffer;
import net.minecraft.util.Direction;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.fml.network.NetworkEvent;

import java.util.function.Supplier;

public class KeyDown {
    private final BlockPos pos;
    private final Direction face;

    public KeyDown(BlockPos pos, Direction face) {
        this.pos = pos;
        this.face = face;
    }

    public static void encode(KeyDown msg, PacketBuffer buffer) {
        buffer.writeBlockPos(msg.pos);
        buffer.writeEnum(msg.face);
    }

    public static KeyDown decode(PacketBuffer buffer) {
        return new KeyDown(buffer.readBlockPos(), buffer.readEnum(Direction.class));
    }

    public static void work(KeyDown packet, Supplier<NetworkEvent.Context> ctx) {
        NetworkEvent.Context context = ctx.get();
        context.enqueueWork(() -> {
            ServerPlayerEntity player = context.getSender();
            if (player != null) {
                World world = player.level;
                BlockPos pos = packet.pos;
                Direction face = packet.face;
                ItemStack stack = player.getMainHandItem();

                if (stack.isEmpty()) {
                    return;
                }

                PutItemAction.put(world, pos, face, stack, player.getDirection(),false);
            }
        });
        context.setPacketHandled(true);
    }
}
